<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ElCard, ElRow, ElCol, ElButton, ElIcon, ElSelect, ElOption, ElDatePicker } from 'element-plus'
import { Search, Refresh, Download, Filter, BarChart3, PieChart, LineChart, Calendar } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 获取当前路由
const route = useRoute()

// 图表引用
const studentScoreChartRef = ref(null)
const courseTrendChartRef = ref(null)
const teacherWorkloadChartRef = ref(null)
const resourceDistributionChartRef = ref(null)

// 筛选条件
const timeRange = ref('month')
const startDate = ref('')
const endDate = ref('')
const classFilter = ref('all')

// 统计数据
const statsData = ref({
  totalStudents: 0,
  totalCourses: 0,
  averageScore: 0,
  activeTeachers: 0
})

// 班级选项
const classOptions = ref([
  { value: 'all', label: '全部班级' },
  { value: '1班', label: '1班' },
  { value: '2班', label: '2班' },
  { value: '3班', label: '3班' },
  { value: '4班', label: '4班' },
  { value: '5班', label: '5班' }
])

// 时间范围选项
const timeRangeOptions = ref([
  { value: 'week', label: '近7天' },
  { value: 'month', label: '近30天' },
  { value: 'quarter', label: '近90天' },
  { value: 'year', label: '近一年' },
  { value: 'custom', label: '自定义' }
])

// 根据路由确定当前显示的图表类型
const getCurrentChartType = () => {
  switch (route.name) {
    case 'student-score-statistics':
      return 'studentScore'
    case 'course-trend-statistics':
      return 'courseTrend'
    case 'teacher-workload-statistics':
      return 'teacherWorkload'
    case 'resource-distribution-statistics':
      return 'resourceDistribution'
    default:
      return 'all' // 默认显示所有图表
  }
}

// 根据路由获取页面标题
const getPageTitle = () => {
  switch (route.name) {
    case 'student-score-statistics':
      return '学生成绩分析'
    case 'course-trend-statistics':
      return '课程趋势分析'
    case 'teacher-workload-statistics':
      return '教师工作量分析'
    case 'resource-distribution-statistics':
      return '资源分布分析'
    default:
      return '统计分析' // 默认标题
  }
}

// 初始化学生成绩分布图表
const initStudentScoreChart = () => {
  if (studentScoreChartRef.value) {
    const chart = echarts.init(studentScoreChartRef.value)
    chart.setOption({
      title: {
        text: '学生成绩分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['人数'],
        bottom: 0
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['0-59', '60-69', '70-79', '80-89', '90-100']
      },
      yAxis: {
        type: 'value',
        name: '人数'
      },
      series: [
        { name: '人数', type: 'bar', data: [] }
      ]
    })

    window.addEventListener('resize', () => chart.resize())
    return chart
  }
  return null
}

// 初始化课程注册趋势图表
const initCourseTrendChart = () => {
  if (courseTrendChartRef.value) {
    const chart = echarts.init(courseTrendChartRef.value)
    chart.setOption({
      title: {
        text: '课程注册趋势',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['注册人数'],
        bottom: 0
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: []
      },
      yAxis: {
        type: 'value',
        name: '注册人数'
      },
      series: [
        { name: '注册人数', type: 'line', smooth: true, data: [] }
      ]
    })

    window.addEventListener('resize', () => chart.resize())
    return chart
  }
  return null
}

// 初始化教师工作量图表
const initTeacherWorkloadChart = () => {
  if (teacherWorkloadChartRef.value) {
    const chart = echarts.init(teacherWorkloadChartRef.value)
    chart.setOption({
      title: {
        text: '教师工作量统计',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '课程数量',
          type: 'pie',
          radius: '55%',
          center: ['50%', '60%'],
          data: [],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    })

    window.addEventListener('resize', () => chart.resize())
    return chart
  }
  return null
}

// 初始化资源使用分布图表
const initResourceDistributionChart = () => {
  if (resourceDistributionChartRef.value) {
    const chart = echarts.init(resourceDistributionChartRef.value)
    chart.setOption({
      title: {
        text: '资源使用分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '资源类型',
          type: 'pie',
          radius: '55%',
          center: ['50%', '60%'],
          data: [],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    })

    window.addEventListener('resize', () => chart.resize())
    return chart
  }
  return null
}

// 生成模拟数据
const generateMockData = () => {
  // 基本统计数据
  statsData.value = {
    totalStudents: Math.floor(Math.random() * 500) + 500,
    totalCourses: Math.floor(Math.random() * 30) + 20,
    averageScore: Math.floor(Math.random() * 15) + 70,
    activeTeachers: Math.floor(Math.random() * 10) + 5
  }

  // 学生成绩分布数据
  const scoreDistribution = [
    Math.floor(Math.random() * 20) + 5,
    Math.floor(Math.random() * 30) + 10,
    Math.floor(Math.random() * 40) + 20,
    Math.floor(Math.random() * 30) + 10,
    Math.floor(Math.random() * 20) + 5
  ]

  // 课程注册趋势数据
  const courseTrendLabels = []
  const courseTrendData = []
  const today = new Date()
  for (let i = 14; i >= 0; i--) {
    const date = new Date(today)
    date.setDate(today.getDate() - i)
    courseTrendLabels.push(`${date.getMonth() + 1}/${date.getDate()}`)
    courseTrendData.push(Math.floor(Math.random() * 50) + 10)
  }

  // 教师工作量数据
  const teacherWorkloadData = [
    { name: '张老师', value: Math.floor(Math.random() * 8) + 2 },
    { name: '李老师', value: Math.floor(Math.random() * 8) + 2 },
    { name: '王老师', value: Math.floor(Math.random() * 8) + 2 },
    { name: '赵老师', value: Math.floor(Math.random() * 8) + 2 },
    { name: '刘老师', value: Math.floor(Math.random() * 8) + 2 }
  ]

  // 资源使用分布数据
  const resourceDistributionData = [
    { name: '教学视频', value: Math.floor(Math.random() * 40) + 30 },
    { name: '文档资料', value: Math.floor(Math.random() * 30) + 20 },
    { name: '作业测试', value: Math.floor(Math.random() * 20) + 10 },
    { name: '课件PPT', value: Math.floor(Math.random() * 15) + 5 },
    { name: '其他资源', value: Math.floor(Math.random() * 10) + 2 }
  ]

  return {
    scoreDistribution,
    courseTrendLabels,
    courseTrendData,
    teacherWorkloadData,
    resourceDistributionData
  }
}

// 更新图表数据
const updateCharts = () => {
  const mockData = generateMockData()
  const chartType = getCurrentChartType()

  // 更新学生成绩分布图表（仅在需要时显示）
  if (chartType === 'all' || chartType === 'studentScore') {
    const studentScoreChart = initStudentScoreChart()
    if (studentScoreChart) {
      studentScoreChart.setOption({
        series: [
          { name: '人数', data: mockData.scoreDistribution }
        ]
      })
    }
  }

  // 更新课程注册趋势图表（仅在需要时显示）
  if (chartType === 'all' || chartType === 'courseTrend') {
    const courseTrendChart = initCourseTrendChart()
    if (courseTrendChart) {
      courseTrendChart.setOption({
        xAxis: {
          data: mockData.courseTrendLabels
        },
        series: [
          { name: '注册人数', data: mockData.courseTrendData }
        ]
      })
    }
  }

  // 更新教师工作量图表（仅在需要时显示）
  if (chartType === 'all' || chartType === 'teacherWorkload') {
    const teacherWorkloadChart = initTeacherWorkloadChart()
    if (teacherWorkloadChart) {
      teacherWorkloadChart.setOption({
        series: [
          {
            data: mockData.teacherWorkloadData
          }
        ]
      })
    }
  }

  // 更新资源使用分布图表（仅在需要时显示）
  if (chartType === 'all' || chartType === 'resourceDistribution') {
    const resourceDistributionChart = initResourceDistributionChart()
    if (resourceDistributionChart) {
      resourceDistributionChart.setOption({
        series: [
          {
            data: mockData.resourceDistributionData
          }
        ]
      })
    }
  }
}

// 刷新数据
const refreshData = () => {
  updateCharts()
}

// 下载数据
const downloadData = () => {
  // 实际应用中这里应该实现数据导出功能
  ElNotification.info('数据下载中...')
}

// 页面加载时初始化
onMounted(() => {
  // 延迟初始化图表，确保DOM已渲染
  setTimeout(() => {
    updateCharts()
  }, 100)
})

// 监听路由变化
watch(route, () => {
  // 延迟更新图表，确保DOM已渲染
  setTimeout(() => {
    updateCharts()
  }, 100)
})
</script>

<template>
  <div class="statistics-container">
    <div class="header">
      <h2>{{ getPageTitle() }}</h2>
      <div class="filter-controls">
        <el-select
          v-model="timeRange"
          placeholder="请选择时间范围"
          style="width: 150px; margin-right: 10px;"
          @change="refreshData"
        >
          <el-option v-for="option in timeRangeOptions" :key="option.value" :label="option.label" :value="option.value" />
        </el-select>
        <template v-if="timeRange === 'custom'">
          <el-date-picker
            v-model="startDate"
            type="date"
            placeholder="开始日期"
            style="width: 150px; margin-right: 10px;"
          />
          <el-date-picker
            v-model="endDate"
            type="date"
            placeholder="结束日期"
            style="width: 150px; margin-right: 10px;"
          />
        </template>
        <el-select
          v-model="classFilter"
          placeholder="请选择班级"
          style="width: 120px; margin-right: 10px;"
          @change="refreshData"
        >
          <el-option v-for="option in classOptions" :key="option.value" :label="option.label" :value="option.value" />
        </el-select>
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon> 刷新
        </el-button>
        <el-button @click="downloadData">
          <el-icon><Download /></el-icon> 导出
        </el-button>
      </div>
    </div>

    <!-- 只有在显示所有统计信息时才显示统计卡片 -->
    <el-row v-if="getCurrentChartType() === 'all'" :gutter="20">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-label">学生总数</div>
            <div class="stat-value">{{ statsData.totalStudents }}</div>
            <div class="stat-trend">+5.2% <span class="trend-up">↑</span></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-label">课程总数</div>
            <div class="stat-value">{{ statsData.totalCourses }}</div>
            <div class="stat-trend">+2.8% <span class="trend-up">↑</span></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-label">平均成绩</div>
            <div class="stat-value">{{ statsData.averageScore }}</div>
            <div class="stat-trend">-1.3% <span class="trend-down">↓</span></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-label">活跃教师</div>
            <div class="stat-value">{{ statsData.activeTeachers }}</div>
            <div class="stat-trend">+3.5% <span class="trend-up">↑</span></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 学生成绩分布图表 -->
    <el-row v-if="getCurrentChartType() === 'all' || getCurrentChartType() === 'studentScore'" :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="chart-card">
          <div class="chart-header">
            <h3>学生成绩分布</h3>
            <el-icon class="chart-icon"><BarChart3 /></el-icon>
          </div>
          <div ref="studentScoreChartRef" style="width: 100%; height: 350px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 课程注册趋势图表 -->
    <el-row v-if="getCurrentChartType() === 'all' || getCurrentChartType() === 'courseTrend'" :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="chart-card">
          <div class="chart-header">
            <h3>课程注册趋势</h3>
            <el-icon class="chart-icon"><LineChart /></el-icon>
          </div>
          <div ref="courseTrendChartRef" style="width: 100%; height: 350px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 教师工作量统计图表 -->
    <el-row v-if="getCurrentChartType() === 'all' || getCurrentChartType() === 'teacherWorkload'" :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="chart-card">
          <div class="chart-header">
            <h3>教师工作量统计</h3>
            <el-icon class="chart-icon"><PieChart /></el-icon>
          </div>
          <div ref="teacherWorkloadChartRef" style="width: 100%; height: 350px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 资源使用分布图表 -->
    <el-row v-if="getCurrentChartType() === 'all' || getCurrentChartType() === 'resourceDistribution'" :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="chart-card">
          <div class="chart-header">
            <h3>资源使用分布</h3>
            <el-icon class="chart-icon"><PieChart /></el-icon>
          </div>
          <div ref="resourceDistributionChartRef" style="width: 100%; height: 350px;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.statistics-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-controls {
  display: flex;
  align-items: center;
}

.stat-card {
  text-align: center;
}

.stat-content {
  padding: 20px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-top: 10px;
}

.stat-trend {
  font-size: 12px;
  color: #909399;
}

.trend-up {
  color: #67c23a;
}

.trend-down {
  color: #f56c6c;
}

.chart-card {
  position: relative;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
}

.chart-icon {
  font-size: 24px;
}

</style>
